﻿/**************************************************************
 *
 * 命名空间：Sgr.DataCategories.Application.Commands.AdministrativeDivisions
 * 创建时间：2025/3/19
 * 描述：更新行政区划命令处理器
 *
 **************************************************************/

using MediatR;
using Microsoft.International.Converters.PinYinConverter;
using Sgr.Application.Commands;
using Sgr.DataCategories.Domain.AdministrativeDivisions;
using Sgr.Domain.Entities;
using Sgr.Domain.Uow;
using Sgr.Exceptions;
using Sgr.Modules;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;

namespace Sgr.DataCategories.Application.Commands.AdministrativeDivisions
{
    /// <summary>
    /// 更新行政区划命令处理器
    /// </summary>
    public class UpdateAdministrativeDivisionCommandHandler
        : IRequestHandler<UpdateAdministrativeDivisionCommand, CommandResult<bool>>
    {
        private readonly IAdministrativeDivisionManage _administrativeDivisionManage;
        private readonly IAdministrativeDivisionRepository _administrativeDivisionRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="administrativeDivisionManage">行政区划管理器</param>
        /// <param name="administrativeDivisionRepository">行政区划仓储</param>
        public UpdateAdministrativeDivisionCommandHandler(
            IAdministrativeDivisionManage administrativeDivisionManage,
            IAdministrativeDivisionRepository administrativeDivisionRepository)
        {
            _administrativeDivisionManage = administrativeDivisionManage;
            _administrativeDivisionRepository = administrativeDivisionRepository;
        }

        /// <summary>
        /// 处理更新行政区划命令
        /// </summary>
        /// <param name="request">命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>处理结果</returns>
        public async Task<CommandResult<bool>> Handle(
            UpdateAdministrativeDivisionCommand request,
            CancellationToken cancellationToken)
        {
            // 查找行政区划实体
            var entity = await _administrativeDivisionRepository.GetAsync(request.Id, cancellationToken);

            if (entity == null)
                return CommandResult.NotFound<bool>("查无数据");

            // 更新行政区划代码
            if (request.Code != entity.Code)
            {
                DomainRuleCheckResult ruleCheckResult = await _administrativeDivisionManage.ValidateCodeIsUniqueAsync(request.Code, request.Id, cancellationToken);
                ruleCheckResult.HandleRule();

                entity.ChangeCode(request.Code);
            }

            //更新行政区划父Id
            if (request.ParentId.HasValue && request.ParentId.Value > 0 && entity.ParentId != request.ParentId.Value)
            {
                var moveResult = await _administrativeDivisionManage.ValidateMoveOperationAsync(
                    entity,
                    request.ParentId.Value,
                    5,
                    cancellationToken);
                if (!moveResult.IsComply)
                    return CommandResult.Invalid<bool>($"更新上级行政区划失败, {moveResult.Message}");
            }

            // 更新基本信息
            string pinyinName = PinYinConverterHelper.ToPinyin(request.Name);
            string pinyinAbbr = PinYinConverterHelper.ToFirstPinyin(request.Name);
            entity.UpdateBasicInfo(
                request.Name,
                request.ShortName,
                pinyinName,
                pinyinAbbr,
                request.Description,
                request.OrderNumber);

            // 更新状态
            if (request.State == EntityStates.Normal)
                await _administrativeDivisionManage.ActivateAsync(entity, cancellationToken);
            else if (request.State == EntityStates.Deactivate)
                await _administrativeDivisionManage.DeactivateAsync(entity, cancellationToken);

            await _administrativeDivisionRepository.UpdateAsync(entity, cancellationToken);

            return CommandResult.Success(true);
        }
    }
}